package plus.easydo.easypush.controller;

import com.taobao.api.ApiException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import plus.easydo.core.result.DataResult;
import plus.easydo.core.result.R;
import plus.easydo.easypush.cache.ChannelCache;
import plus.easydo.easypush.dingtalk.DingTalkConst;
import plus.easydo.easypush.dingtalk.DingTalkWorkNoticeEnum;
import plus.easydo.easypush.dingtalk.model.DingTalkSelectUsers;
import plus.easydo.easypush.dingtalk.model.DingTalkWorkNotice;
import plus.easydo.easypush.dingtalk.model.DingTalkWorkNoticeMessage;
import plus.easydo.easypush.dingtalk.service.DingTalkService;
import plus.easydo.easypush.entity.ChannelInfo;
import plus.easydo.easypush.oauth.AuthStateRedisCache;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author laoyu
 * @version 1.0
 * @date 2022/2/26
 */
@RestController
@Api(tags = "钉钉相关")
@RequestMapping("/dingTalk")
public class DingTalkController {

    @Autowired
    DingTalkService dingTalkService;

    @Autowired
    AuthStateRedisCache authStateRedisCache;

    @Autowired
    ChannelCache channelCache;

    @ApiOperation("批量发送自定义钉钉通知")
    @PostMapping("/workNotice/{channelId}/")
    public R<Object> workNotice(@RequestHeader("token")String token,@PathVariable("channelId")Long channelId, @RequestBody List<DingTalkWorkNotice> dingTalkWorkNoticeList) {
        ChannelInfo channelInfo = channelCache.getChannelByTokenAndChannelId(token,channelId);
        AtomicInteger count = new AtomicInteger();
        dingTalkWorkNoticeList.forEach(dingTalkWorkNotice -> {
            DingTalkSelectUsers dingTalkSelectUsers = dingTalkWorkNotice.getDingTalkSelectUsers();
            DingTalkWorkNoticeMessage dingTalkWorkNoticeMessage = dingTalkWorkNotice.getDingTalkWorkNoticeMessage();
            String messageType = dingTalkWorkNotice.getMessageType();
            try {
                boolean result = dingTalkService.workNotice(dingTalkSelectUsers, dingTalkWorkNoticeMessage, DingTalkWorkNoticeEnum.getEnumByType(messageType),channelInfo);
                if (result) {
                    count.incrementAndGet();
                }
            } catch (ApiException e) {
                e.printStackTrace();
            }
        });
        return DataResult.okMsg("共处理" +dingTalkWorkNoticeList.size()+"组,成功"+count.get()+"组");
    }
}
